﻿package com.skillscoach {
	import alducente.services.WebService;
	import flash.display.MovieClip;
	import flash.media.Microphone;
	import org.bytearray.micrecorder.encoder.WaveEncoder;
	import org.bytearray.micrecorder.MicRecorder;
	import flash.events.MouseEvent;
	import flash.events.Event;
	import org.bytearray.micrecorder.events.RecordingEvent;
	import flash.system.Security;
	import fl.transitions.Tween;
	import fl.transitions.easing.Strong;
	import flash.net.FileReference;
	import flash.display.LoaderInfo;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import org.as3wavsound.WavSound;
	import flash.utils.ByteArray;
	import flash.external.ExternalInterface;
	import flash.media.SoundChannel;
	
	
	
	public class RecAudio extends MovieClip {
		public var stageClip:MovieClip = this as MovieClip;
		private var ws:WebService;
		private var mic:Microphone;
		private var waveEncoder:WaveEncoder = new WaveEncoder();
		private var recorder:MicRecorder = new MicRecorder(waveEncoder);
		private var recBar:RecBar = new RecBar();
		private var tween:Tween;
		private var fileReference:FileReference = new FileReference();
		private var paramObj:Object;
		private var recordedAudioFilePath:String = "http://media.onlineskillscoach.com/bic/audios";
		private var recordedAudioFileName:String;
		private var wavAudio:WavSound;
		private var wav:URLLoader;
		private var audioURLReq:URLRequest;
		
		public function RecAudio() {
			Security.allowDomain("*");
			
			paramObj = LoaderInfo(this.root.loaderInfo).parameters;
			//result_txt.text = "MemberId  : " + paramObj.MemberId + "ApplicationId  :  " + paramObj.ApplicationId + "  ManagerId  :  " + paramObj.ManagerId;
			// constructor code
			
			enableBtn(delBtn, false);
			
			alphaLayer.enabled = false;
			saveBtn.alpha = .5;
			recButton.stop();
			activity.stop();

			mic = Microphone.getMicrophone();
			mic.setSilenceLevel(70);
			mic.gain = 100;
			//mic.setLoopBack(true);
			//mic.setUseEchoSuppression(true);
			
			Security.showSettings("2");
			loadWSDL();
			addListeners();
		}
		
		private function addListeners():void
		{
			recButton.addEventListener(MouseEvent.MOUSE_UP, startRecording);
			recorder.addEventListener(RecordingEvent.RECORDING, recording);
			recorder.addEventListener(Event.COMPLETE, recordComplete);
			activity.addEventListener(Event.ENTER_FRAME, updateMeter);
			closeBtn.addEventListener(MouseEvent.CLICK, closeApp);
		}
		
		private function closeApp(evt:MouseEvent):void
		{
			ExternalInterface.call("CompleteRecording");
		}
		private function loadWSDL():void
		{
			ws = new WebService();
			ws.addEventListener(Event.CONNECT, wsdlConnected);
			//change here
				//ws.connect("http://testgic.onlineskillscoach.com/ATandT.asmx?WSDL");
				ws.connect("http://api.onlineskillscoach.com/ATandT.asmx?WSDL");
				//ws.connect(paramObj.XMLServicePath + "?WSDL");
		}
		private function wsdlConnected(evt:Event):void
		{
			trace("web service  connected");
			alphaLayer.visible = false;

		}

		private function startRecording(e:MouseEvent):void
		{
			if (mic != null)
			{
				trace("came");
				recorder.record();
				e.target.gotoAndStop(2);

				recButton.removeEventListener(MouseEvent.MOUSE_UP, startRecording);
				recButton.addEventListener(MouseEvent.MOUSE_UP, stopRecording);
				addChild(recBar);

				tween = new Tween(recBar,"y",Strong.easeOut, -  recBar.height,0,1,true);
			}
		}

		private function stopRecording(e:MouseEvent):void
		{
			recorder.stop();

			mic.setLoopBack(false);
			e.target.gotoAndStop(1);

			recButton.removeEventListener(MouseEvent.MOUSE_UP, stopRecording);
			
			recButton.addEventListener(MouseEvent.MOUSE_UP, startRecording);

			tween = new Tween(recBar,"y",Strong.easeOut,0, - recBar.height,1,true);
		}

		private function updateMeter(e:Event):void
		{
			activity.gotoAndPlay(100 - mic.activityLevel);
		}

		private function recording(e:RecordingEvent):void
		{
			var currentTime:int = Math.floor(e.time / 1000);

			recBar.counter.text = String(currentTime);

			if (String(currentTime).length == 1)
			{
				recBar.counter.text = "00:0" + currentTime;
			}
			else if (String(currentTime).length == 2)
			{
				recBar.counter.text = "00:" + currentTime;
			}
			else if (String(currentTime).length == 2)
			{
				recBar.counter.text = "00:" + currentTime;
			}
		}

		private function recordComplete(e:Event):void
		{
			saveBtn.alpha = 1;
			stageClip.saveBtn.addEventListener(MouseEvent.CLICK, saveAudio);
			stageClip.saveBtn.buttonMode = true;
			//fileReference.save(recorder.output, "recording.wav");
		}
		
		
		private function saveAudio(evt:MouseEvent):void
		{
			enableBtn(recButton, false);
			recButton.removeEventListener(MouseEvent.MOUSE_UP, startRecording);
			result_txt.text = "Uploading your recorded audio...";
			try
			{
				recorder.stop();
				activity.alpha = 0;
				stageClip.recordBtn.gotoAndStop(1);
			}
			catch (e)
			{

			}


			if (recorder.output)
			{
				//change here
				ws.SaveAudio(saveFrameResponse, '1', '1', '3 ', Base64.encode(recorder.output));
				//ws.SaveAudio(saveFrameResponse, paramObj.ApplicationId , paramObj.MemberId, paramObj.ManagerId, Base64.encode(recorder.output));
			}
			else
			{
				trace("null");
			}
		}
		
		private function saveFrameResponse(serviceResponse:XML):void
		{
			enableBtn(delBtn, true);
			delBtn.addEventListener(MouseEvent.CLICK, deleteRecordedAudio);
			stageClip.saveBtn.removeEventListener(MouseEvent.CLICK, saveAudio);
			stageClip.saveBtn.buttonMode = false;
			recButton.alpha = 1;
			recButton.enabled = true;
			stageClip.saveBtn.alpha = .5;
			var str:String = String(serviceResponse.children().children().children());
			result_txt.text = str;
			trace(serviceResponse);
			trace(str);
			recordedAudioFileName = str;
			// pleasewaitMc.visible = false;
			//recorder.output = null;
			enableBtn(recButton, false);
			recButton.gotoAndStop(3);
			loadRecordedAudio();
			
			trace("saved")
			
		}
		private function deleteRecordedAudio(evt:MouseEvent):void
		{
			//change here
			ws.DeleteRecordedAudio(delRecAudioResponse, recordedAudioFileName, paramObj.ManagerId);
			//ws.DeleteRecordedAudio(delRecAudioResponse, recordedAudioFileName, "3");
		}
		private function delRecAudioResponse(serviceResponse:XML):void
		{
			trace(serviceResponse);
			wavAudio = null;
			result_txt.text = "Recorded Audio is deleted";
		}
		private function loadRecordedAudio():void
		{
			
			wav = new URLLoader();
			audioURLReq = new URLRequest(recordedAudioFilePath + "/" + recordedAudioFileName);
			//result_txt.text = "Loading audio please wait...";
			result_txt.text = recordedAudioFilePath + "/" + recordedAudioFileName;
			
			wav.dataFormat = 'binary';
			wav.load(audioURLReq);
			wav.addEventListener(Event.COMPLETE, enableRecordedAudioPlay);
		}
		private function enableRecordedAudioPlay(evt:Event):void
		{
			
			var myChannel:SoundChannel = new SoundChannel();
			result_txt.text = "Click to play recorded audio";
			wavAudio = new WavSound(evt.target.data as ByteArray);
			myChannel.soundTransform
			enableBtn(recButton, true);
			
			recButton.addEventListener(MouseEvent.CLICK , playRecordedAudio);
			
		}
		private function playRecordedAudio(evt:MouseEvent):void
		{
			recButton.gotoAndStop(4);
			recButton.removeEventListener(MouseEvent.CLICK, playRecordedAudio);
			recButton.addEventListener(MouseEvent.CLICK, stopRecordedAudio);
			enableBtn(recButton, true);
			wavAudio.play();
			
			
		}
		
		private function stopRecordedAudio(evt:MouseEvent):void
		{
			recButton.removeEventListener(MouseEvent.CLICK, stopRecordedAudio);
			recButton.addEventListener(MouseEvent.CLICK , playRecordedAudio);
			recButton.gotoAndStop(3);
		}
		private function enableBtn(btn:MovieClip, bool:Boolean):void
		{
			if(bool)
			{
				btn.alpha = 1;
				btn.enabled = bool;
			}else {
				btn.alpha = .5;
				btn.enabled = bool;
				}
		}
	}
	
}
